package com.huaqin.punan.actupdate;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.huaqin.punan.actupdate.UpdateService.MyBinder;
import com.huaqin.punan.actupdate.UpdateService.UpdateData;

public class MainActivity extends Activity {
	public static final String TAG = "MainActivity";
	private TextView tv;
	private UpdateService.MyBinder mBinder;
	private Button mBtnStart;
	
	private ServiceConnection mServiceConnection = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mBinder=(MyBinder) service;
            tv.setText("已连接");
			
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		tv = (TextView)findViewById(R.id.tv);
		mBtnStart = (Button)findViewById(R.id.btn);
		
		Intent intent = new Intent(this,UpdateService.class);
		bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
		
		mBtnStart.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mBinder != null){
					mBinder.setDate(tv, new UpdateData(){
						@Override
						public void update(TextView tv, int data) {
							// TODO Auto-generated method stub
							tv.setText(data+"");
						}});
				}else{
					Toast.makeText(getApplicationContext(), "connect failed", Toast.LENGTH_SHORT).show();
				}
				
			}});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unbindService(mServiceConnection);
	}

}
